﻿using System.Linq;
using Flagwind.Web;

namespace Flagwind.ComponentModel
{
    /// <summary>
    /// 通讯响应命令扩展类
    /// </summary>
    public static class ResponseInstructionExtensions
    {
		/// <summary>
		/// 将通讯响应命令解析为 API 响应。
		/// </summary>
		/// <typeparam name="T">响应命令的内容返回类型。</typeparam>
		/// <param name="response">响应命令实例。</param>
		/// <returns>API 响应实例。</returns>
		public static ApiResult ToApiResult<T>(this ResponseInstruction<T> response)
        {
            switch (response.Status)
            {
                case ResponseStatus.Success:
                    return new ApiResult(ApiStatusCode.Success, response.Result, response.Message);
                case ResponseStatus.Failure:
                    return new ApiResult(ApiStatusCode.Failure, response.Result, response.Message);
                case ResponseStatus.ValidationError:
                    var errors = response.ValidationErrors.Select(e => new ValidationError(e.MemberNames.FirstOrDefault(), e.ErrorMessage));
                    return new ApiResult(ApiStatusCode.InvalidParam, errors, response.Message);
                case ResponseStatus.InvalidSign:
                    return new ApiResult(ApiStatusCode.InvalidSign, null, response.Message);
                case ResponseStatus.Unauthorized:
                    return new ApiResult(ApiStatusCode.Unauthorized, null, response.Message);
                case ResponseStatus.SessionLost:
                    return new ApiResult(ApiStatusCode.SessionLost, null, response.Message);
                case ResponseStatus.ServerError:
                    return new ApiResult(ApiStatusCode.ServerError, null, response.Message);
            }

            return new ApiResult(999);
        }
    }
}
